import { templateIcons } from '@/api/base-config.js'
import { useEffect } from 'react'
import { useState } from 'react'
import { Dropdown, Space } from 'antd'
import { DownOutlined } from '@ant-design/icons'
import ksIcon from '@/assets/node-svg/ks.svg'
import gcIcon from '@/assets/node-svg/gc.svg'
import kxgcIcon from '@/assets/node-svg/kxgc.svg'
import jcIcon from '@/assets/node-svg/jc.svg'
import sjIcon from '@/assets/node-svg/sj.svg'
import ljIcon from '@/assets/node-svg/lj.svg'
import './index.less'

export const defaultIconMap = {
  ks: ksIcon,
  gc: gcIcon,
  kxgc: kxgcIcon,
  jc: jcIcon,
  sj: sjIcon,
  lj: ljIcon,
}

export const getIcon = (attachId) => {
  let url = ''
  if (iconKeys.includes(attachId)) {
    url = defaultIconMap[attachId]
  } else {
    url = `/api/sys/attach/download?attachId=${attachId}`
  }
  return url
}

let iconKeys = Object.keys(defaultIconMap)

const IconSelect = ({ value, onChange }) => {
  const [iconList, setIconList] = useState([])
  const [currentIcon, setCurrentIcon] = useState(value)

  const requestIconList = () => {
    templateIcons().then((res) => {
      setIconList(res.data)
    })
  }

  const onSelect = (item) => {
    let icon = item ? item.attach_id : null
    setCurrentIcon(icon)
    onChange(icon)
  }

  useEffect(() => {
    requestIconList()
  }, [])

  const items = iconList.map((item) => {
    return {
      ...item,
      label: (
        <img onClick={() => onSelect(item)} src={getIcon(item.attach_id)} alt={item.attach_name}/>
      ),
    }
  })

  return (
    <Dropdown menu={{ items }}>
      <Space onClick={(e) => e.preventDefault()} className='tip-text'>
        { currentIcon ? <img src={getIcon(currentIcon)} /> : <span>请选择</span>}
        <DownOutlined />
      </Space>
    </Dropdown>
  )
}

IconSelect.displayName = 'IconSelect'

export default IconSelect
